package com.application.mylibrary.base;


import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.CircularProgressDrawable;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;

import com.application.mylibrary.R;
import com.application.mylibrary.utils.DensityUtil;
import com.application.mylibrary.utils.EventBusUtils;
import com.application.mylibrary.utils.StatusBarUtil;
import com.githang.statusbar.StatusBarCompat;

/**
 * Created by lixuce on 2019/8/6.
 */
public abstract class BaseActivity extends AppCompatActivity {
    protected static final String TAG = "BaseActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setNoLockScreen();
        setStatusBar();

        beforeInit();
        if (getLayoutId() != 0) {
            setContentView(getLayoutId());
        }
        if (registerEventBus()) {
            EventBusUtils.register(this);
        }
//        ARouter.getInstance().inject(this);

    }

    public boolean registerEventBus() {
        return false;
    }

    //界面初始化之前  一般是做些获取传值
    public abstract void beforeInit();

    //界面的layout
    public abstract int getLayoutId();


    private View progress;

    //显示load弹窗
    public void showloadDialog() {
        if (isFinishing())
            return;
        if (progress == null) {
            progress = LayoutInflater.from(this).inflate(R.layout.include_activity_progressbar1, null);
            CircularProgressDrawable drawable = new CircularProgressDrawable(this);
            drawable.setStyle(CircularProgressDrawable.LARGE);
            drawable.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
            drawable.start();
            progress.setBackground(drawable);
        } else {
            // 避免重复添加的bug
            if (progress.getParent() != null || progress.getVisibility() == View.VISIBLE) {
                return;
            }
        }
        FrameLayout parent = ((FrameLayout) getWindow().getDecorView());
        int width = DensityUtil.dp2px(this, 20);
        FrameLayout.LayoutParams la = new FrameLayout.LayoutParams(width, width);
        la.gravity = Gravity.CENTER;
        progress.setLayoutParams(la);
        parent.addView(progress);
    }

    //loading弹窗消失
    public void hideLoadDialog() {
        if (isFinishing()) {
            return;
        }
        if (progress != null && progress.getParent() != null) {
            FrameLayout parent = ((FrameLayout) getWindow().getDecorView());
            parent.removeView(progress);
            progress = null;
        }
    }

    //带有动画的跳转
    public void startActivityAnim(Intent intent) {
        startActivity(intent);
        overridePendingTransition(0, 0);
    }

    //带有动画的结束页面
    public void finishAnim() {
        finish();
        overridePendingTransition(0, 0);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finishAnim();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (registerEventBus()) {
            EventBusUtils.unregister(this);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //获取当前activity焦点
            View view = getCurrentFocus();
            if (isHideInput(view, ev)) {
                HideSoftInput(view.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);//事件向下分发
    }

    // 判定是否需要隐藏
    private boolean isHideInput(View v, MotionEvent ev) {
        if (v != null && (v instanceof EditText)) {
            int[] I = {0, 0};
            v.getLocationInWindow(I);//控件在其父窗口中的坐标位置
            int left = I[0], top = I[1], bootom = top + v.getHeight(), right = left + v.getWidth();
            //判断点击区域是否为有效区域，并返回true 或 false
            if (ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bootom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    // 隐藏软键盘
    private void HideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void setStatusBar() {
        // unknown null
        if (this.isFinishing()) {
            return;
        }

//        initStatusBar();
//        if(ViewUtils.getBoolean(R.bool.status_bar_is_transparent)){
//            initStatusBar();
//        }else {
            int colorRes = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? R.color.white : R.color.black;
            StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, colorRes), true);
//        }
    }


    private void initStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    protected void setNoLockScreen() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

}
